<template>
  <div class="search">
    <div class="search-header">
      <div class="search-header-input">
        <van-icon
          v-if="!isWxPlatfrom"
          name="arrow-left"
          @click="back"
          class="search-header-input-back"
        />
        <van-search
          class="search-header-input-box"
          v-model="searchKeyWords"
          placeholder="请输入搜索关键词"
        />
        <van-button
          type="primary"
          round
          class="search-header-input-btn"
          @click="searchEvent"
          >搜索</van-button
        >
      </div>
      <div class="search-header-tabs">
        <van-tabs v-model:active="searchActiveIndex" @change="tabsChange">
          <van-tab title="单曲"></van-tab>
          <van-tab title="歌单"></van-tab>
        </van-tabs>
      </div>
    </div>
    <div class="search-container">
      <infinite-scroll
        :loadable="canLoad"
        :distance="distance"
        :infiniteEvent="addMore"
      >
        <div v-if="searchActiveIndex === 0">
          <music-item
            v-for="(item, index) in musicList"
            :key="index"
            :musicIndex="index"
            :id="item.id"
            :name="item.name"
            :artists="item.artists"
          ></music-item>
        </div>
        <div v-else>
          <play-list
            style="margin: 10px"
            v-for="(item, index) in musicList"
            :key="index"
            :id="item.id"
            :creater="item.creator.nickname"
            :name="item.name"
            :count="item.trackCount"
            :coverImgUrl="item.coverImgUrl"
          ></play-list>
        </div>
        <div v-if="musicList.length" class="search-addmore">
          {{ musicList.length >= dataCount ? "加载完毕" : "加载更多中" }}
        </div>
      </infinite-scroll>
    </div>
  </div>
</template>

<script lang='ts'>
import { defineComponent, reactive, toRefs, ref, nextTick } from "vue";
import { InfiniteScroll, MusicItem, PlayList } from "@/components";
import { Toast } from "vant";
import { useCurrentInstance } from "@/utils/hooks";
import { getCurrentPlatfrom } from "ych-js-sdk/lib/sdk";
import { EPlatfrom } from "ych-js-sdk/lib/type/platfrom";
import { httpService } from "@/core/http";
import api from "@/api";

export enum ESearchType {
  /** 单曲 */
  music = 0,
  /** 歌单 */
  playlist = 1,
}

export default defineComponent({
  name: "Search",
  components: {
    InfiniteScroll,
    MusicItem,
    PlayList,
  },
  setup() {
    const _this = useCurrentInstance();
    // 判断是否微信环境
    const isWxPlatfrom = ref<boolean>(
      [EPlatfrom.WECHAT, EPlatfrom.MINIPROGRAME].includes(
        getCurrentPlatfrom as EPlatfrom
      )
    );
    const state = reactive({
      searchKeyWords: "",
      searchActiveIndex: ESearchType.music,
      musicList: [],
      canLoad: true,
      dataCount: 99999,
      distance: 15,
      pageNum: 0,
      pageSize: 20,
    });
    const addMore = () => {
      state.canLoad = false;
      state.searchActiveIndex === ESearchType.music
        ? getMusicList()
        : getPlayList();
    };
    /** tabs改变 */
    const tabsChange = (num: ESearchType) => {
      state.searchActiveIndex = num;
      searchEvent();
    };
    /** 点击搜索 */
    const searchEvent = () => {
      if (!state.searchKeyWords.trim()) {
        state.searchKeyWords = "";
        state.musicList = [];
        state.pageNum = 0;
        state.canLoad = true;
        state.dataCount = 99999;
        return;
      }
      state.pageNum = 0;
      state.musicList = [];
      nextTick(() => {
        const { searchActiveIndex } = state;
        if (searchActiveIndex === ESearchType.music) {
          getMusicList();
        } else if (searchActiveIndex === ESearchType.playlist) {
          getPlayList();
        }
      });
    };
    /** 搜索单曲 */
    const getMusicList = () => {
      const loader = Toast.loading("加载中");
      httpService("GET", api.search, {
        type: 1,
        csrf_token: "hlpretag=",
        hlposttag: "",
        offset: state.pageNum,
        total: true,
        limit: state.pageSize,
        s: state.searchKeyWords,
      })
        .then((res: any) => {
          const { code, result } = res;
          if (code === 200 && result) {
            const { songCount, songs } = result;
            state.musicList = state.musicList.concat(songs);
            state.dataCount = songCount;
            state.pageNum++;
          } else {
            Toast.fail("服务器错误，请稍后重试");
          }
        })
        .finally(() => {
          state.canLoad = true;
          loader.clear();
        });
    };
    /** 搜索歌单 */
    const getPlayList = () => {
      const loader = Toast.loading("加载中");
      httpService("GET", api.search, {
        type: 1000,
        csrf_token: "hlpretag=",
        hlposttag: "",
        offset: state.pageNum,
        total: true,
        limit: state.pageSize,
        s: state.searchKeyWords,
      })
        .then((res: any) => {
          const { code, result } = res;
          if (code === 200 && result) {
            const { playlistCount, playlists } = result;
            state.musicList = state.musicList.concat(playlists);
            state.dataCount = playlistCount;
            state.pageNum++;
          } else {
            Toast.fail("服务器错误，请稍后重试");
          }
        })
        .finally(() => {
          state.canLoad = true;
          loader.clear();
        });
    };
    /** 返回上一页 */
    const back = () => {
      _this.goBack();
    };
    return {
      ...toRefs(state),
      addMore,
      searchEvent,
      tabsChange,
      getMusicList,
      getPlayList,
      back,
      isWxPlatfrom,
    };
  },
});
</script>

<style lang='scss' scoped>
.search {
  @extend .screen_page;
  padding-bottom: 50px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  & > div {
    width: 100%;
  }
  .search-header {
    .search-header-input {
      padding: 2px 10px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .search-header-input-back {
        color: #707070;
        width: 20px;
        height: 30px;
        text-align: left;
        line-height: 30px;
      }
      .search-header-input-box {
        flex: 1;
        :deep() .van-search__content {
          border-radius: 15px;
        }
      }
      .search-header-input-btn {
        height: 30px;
        @include systemBackColor();
        @include systemBorderStyle(1px);
        letter-spacing: 1px;
      }
    }
    .search-header-tabs {
      border-top: 1px solid #f0f0f0;
      border-bottom: 1px solid #f0f0f0;
      :deep() .van-tabs__line {
        @include systemBackColor();
        letter-spacing: 2px;
        border-radius: 5px;
        width: 20px;
      }
      :deep() .van-tabs__text {
        color: #707070;
      }
    }
  }
  .search-container {
    height: calc(100% - 110px);
  }
  .search-addmore {
    padding: 5px 10px;
    font-size: 14px;
    color: #707070;
    text-align: center;
  }
}
</style>